<template>
  <div class="batch-booking-area">
    <div class="middle">
      <bread-crumb class="bread-crumb-padding" :list="breadCrumb"></bread-crumb>
      <tab-list :list="tabList"></tab-list>
      <div class="flx-row-bw" style="margin-top: 17px">
        <div class="left-area">
          <div class="box" style="position: relative">
            <Spin :withIcon="true" v-if="loading"></Spin>
            <div class="top-area flx-col-s-s" style="margin-bottom: 26px">
              <h3 class="title-h3" style="margin-left: 0; margin-bottom: 10px">
                批量预订域名
              </h3>
              <!-- <div class="button" style="margin-bottom: 10px;">导入域名列表</div> -->
              <div class="w-p-100" style="position: relative">
                <Input
                  v-model="dnText"
                  wrap="hard"
                  type="textarea"
                  :autosize="{ minRows: 10, maxRows: 10 }"
                  @on-keyup="getDNNumber"
                  @on-blur="getAvailableDN"
                  placeholder="每行1个域名，可按Enter键进行换行，最多500个域名"
                />
                <span class="c-g number-tips">{{ dnNumber }}/500</span>
              </div>
            </div>
            <h3 class="title-h3" style="margin: 0 0 15px 30px">
              请选择预订通道
            </h3>
            <RadioGroup class="w-p-100" v-model="channelSelect">
              <table class="table-area">
                <thead>
                  <tr>
                    <th>
                      <div class="line-style">通道名称</div>
                    </th>
                    <th>
                      <div class="line-style">成功率</div>
                    </th>
                    <th>
                      <div class="line-style">起拍价格</div>
                    </th>
                    <th>
                      <div class="line-style">预订保证金</div>
                    </th>
                    <th>
                      <div class="line-style">注册商数量</div>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="(item, index) in channelList"
                    :key="index"
                    :class="[(index + 1) % 2 != 0 ? 'lc-f' : 'lc-F9FAFB']"
                  >
                    <td>
                      <div class="line-style-left">
                        <Radio
                          :label="item.id"
                          class="flx-row-s-c"
                          style="display: flex"
                        >
                          <span
                            class="strong-f f-ell-sin"
                            :title="item.channelName"
                            >{{ item.channelName }}</span
                          >
                        </Radio>
                      </div>
                    </td>
                    <td>
                      <div class="line-style">
                        <span class="normal-f f-ell-sin"
                          >{{ item.successRate }}%</span
                        >
                      </div>
                    </td>
                    <td>
                      <div class="line-style">
                        <span class="normal-f f-ell-sin"
                          >￥{{ item.bookPrice }}元</span
                        >
                      </div>
                    </td>
                    <td>
                      <div class="line-style">
                        <span class="normal-f f-ell-sin"
                          >￥{{ item.bookBond }}元</span
                        >
                      </div>
                    </td>
                    <td>
                      <div class="line-style">
                        <span class="normal-f f-ell-sin"
                          >{{ item.registrantCount }}个</span
                        >
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </RadioGroup>
            <div class="flx-row-s-c check-area">
              <Checkbox v-model="agree"></Checkbox>
              我同意
              <span @click="seriveRuleModelShow = true"
                >《{{ seriveRuleTitle }}》</span
              >
              并已阅读
              <span @click="ruleModelShow = true">《{{ ruleTitle }}》</span>
            </div>
            <div class="submit-button" @click="batchBookingfilter">
              立即预订
            </div>
          </div>
        </div>
        <div class="right-area">
          <h3 class="title-h3" style="margin: 20px 19px 13px">推荐预订</h3>
          <table class="table-area">
            <tbody>
              <tr
                v-for="(item, index) in recommendList"
                :key="index"
                :class="[(index + 1) % 2 != 0 ? 'lc-f' : 'lc-F9FAFB']"
              >
                <td>
                  <div class="line-style-left">
                    <span class="normal-f f-ell-sin" title="">{{
                      item.name
                    }}</span>
                  </div>
                </td>
                <td>
                  <div class="line-style">
                    <span class="normal-f f-ell-sin">{{ item.meaning }}</span>
                  </div>
                </td>
                <td>
                  <div class="line-style">
                    <div class="button button-size" @click="add(item.name)">
                      加入预订
                    </div>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="bottom-area">
        <h3 class="title-h3" style="margin-left: 0">抢注预订须知</h3>
        <p v-for="(item, index) in tips" :key="index">{{ item }}</p>
      </div>
    </div>
    <b-b-check-result-modal
      :show.sync="checkResultModalShow"
      :sucList="sucList"
      :failList="failList"
      @delete-item="deleteItem"
      @check-submit="checkSubmit"
    ></b-b-check-result-modal>
    <b-b-order-check-modal
      :show.sync="orderCheckModalShow"
      :loading.sync="orderCheckLoading"
      @submit="orderCheckSubmit"
    >
      <div class="w-p-100 b-b-order-check-modal-main c-d2 f-14">
        <p>您选择的通道是：{{ selectChannelName }}</p>
        <p>
          抢注价格： {{ selectBookPrice }}元/个，保证金：{{
            selectBookBond
          }}元/个
        </p>
        <p>
          预订域名数量：{{ sucList.length }}个，保证金总计：{{
            selectBookBond * sucList.length
          }}元
        </p>
        <p style="margin-top: 15px">
          抢注失败保证金全额退款，可提现，预订成功后不能取消！
        </p>
        <p class="c-r f-16" style="text-align: center">确认要预订吗？</p>
      </div>
    </b-b-order-check-modal>
    <pay-modal
      :show.sync="payModalShow"
      :sumPayable="sumPayable"
      :orderNo="orderNo"
      @start-pay="startPay"
    >
      <div class="flx-row-bw-c">
        <span class="f-16 c-d2"
          >预订域名数量：<span class="f-18 f-w-600 c-o"
            >{{ sucList.length }}个</span
          ></span
        >
        <span class="f-16 c-d2"
          >预订保证金：<span class="f-18 f-w-600 c-r"
            >￥{{ bondMoney }}</span
          ></span
        >
        <span class="f-16 c-d2"
          >应付金额：<span class="f-18 f-w-600 c-gr"
            >￥{{ sumPayable }}</span
          ></span
        >
      </div>
    </pay-modal>
    <order-success-modal
      :show.sync="orderSuccessModalShow"
    ></order-success-modal>
    <to-login-modal
      :show.sync="loginModelShow"
      @toLogin="toLogin"
    ></to-login-modal>
    <rule-modal
      :show.sync="ruleModelShow"
      :content="ruleContent"
      :title="ruleTitle"
    ></rule-modal>
    <rule-modal
      :show.sync="seriveRuleModelShow"
      :content="seriveRuleContent"
      :title="seriveRuleTitle"
    ></rule-modal>
  </div>
</template>

<script>
import { bookingChannel } from "@/utils/publicData";
import { debounce, trimStr } from "@/utils/format";
import {
  batchBookingfilter,
  createBatchOrder,
  getOrderStatus,
} from "@/api/user";
import { hotBooking } from "@/api/data";
import axios from "axios";
const bottomInfoUrl =
  process.env.NODE_ENV === "development"
    ? config2.bottomInfoUrl.dev
    : config2.bottomInfoUrl.pro;
const webScoketUrl =
  process.env.NODE_ENV === "development"
    ? config2.webScoketUrl.dev
    : config2.webScoketUrl.pro;
export default {
  name: "VipBatchbooking",
  components: {
    toLoginModal: () => import("_c/modal/toLoginModal/toLoginModal.vue"),
    bBCheckResultModal: () =>
      import("_c/modal/bBCheckResultModal/bBCheckResultModal.vue"),
    bBOrderCheckModal: () =>
      import("_c/modal/bBOrderCheckModal/bBOrderCheckModal.vue"),
    payModal: () => import("_c/modal/payModal/payModal.vue"),
    orderSuccessModal: () =>
      import("_c/modal/orderSuccessModal/orderSuccessModal.vue"),
    ruleModal: () => import("_c/modal/ruleModal/ruleModal.vue"),
  },
  data() {
    return {
      ruleModelShow: false,
      ruleContent: "",
      ruleTitle: "",
      seriveRuleModelShow: false,
      seriveRuleContent: "",
      seriveRuleTitle: "",
      loading: false,
      orderCheckLoading: false,
      breadCrumb: [{ name: "批量预订", to: "/bookDetail" }],
      tabList: [
        {
          name: "预订域名",
          to: "/dnbooking",
        },
        {
          name: "批量预订",
          to: "/batchbooking",
        },
        {
          name: "我的预订",
          other: true,
          to: "/user/mybookings",
        },
        {
          name: "预订提醒",
          other: true,
          to: "/user/reminder",
        },
      ],
      tips: [
        "1、当您提交抢注预订订单并交纳保证金后，本站会为您预订域名;",
        "2、如有多人预订同一个域名(且预订价格相同)，预订成功后则需要进行竞价，竞价结束价高者得;",
        "3、如您预订的域名只有您一人预订，那么预订成功后，您直接得标，无需竞价;",
        "4、如果预订失败，系统自动退还预订保证金(可以提现);",
        "5、如果预订成功后您只需要付相应的预订价格即可，无需另付其它费用(抢注预订价格，包含了域名的注册费用，预订成功后大部分域名可直接解析使用);",
        "6、已经预订的域名无法取消预订;",
        "7、预订结果:部分平台在域名预订失败后的30个工作日，会继续尝试着为用户继续预订该域名，或修正错误处理为失败的域名，成功后修正域名预订状态并且扣除相应款项，本站会相应修改预订结果和扣款;",
        "8、域名得标后，系统将自动从您的可用余额中扣除相应款项。如余额不足，请在72小时内补齐;若未补齐，视为您已经违约，平台将有权对域名进行拍卖或变卖。",
        "9、如您违约，平台有权做以下操作:扣除违约域名对应的保证金，违约账号将被限制使用易名旗下所有服务，与违约账号关联的账号将被限制使用预订服务。违约域名可由平台进行处理，用于补偿您的违约对平台造成的损失。",
        "10、预订的域名不得用于制作钓鱼诈骗色情等非法网站，发现一律封锁域名，封锁帐户，费用不退，并且将违法帐户信息上报公安部门，后果自负，谢谢合作!",
        "11、由我司通道抢注成功的域名将在您支付尾款后7天内交割给您;由于注册局的转移限制，由合作商通道抢注成功的域名将于域名竞价结衷后的60天〔含60天]之内交割给您，请您谅解。",
      ],
      dnText: "",
      dnNumber: 0,
      dnSet: new Set(),
      channelList: [],

      // 表单数据
      agree: false,
      channelSelect: null,

      // 确认订单数据
      selectChannelName: "",
      selectBookPrice: "",
      selectBookBond: "",

      // 推荐预订
      recommendList: [],

      // 弹框提示
      checkResultModalShow: false,
      sucList: [],
      failList: [],
      orderCheckModalShow: false,
      loginModelShow: false,
      payModalShow: false,
      orderSuccessModalShow: false,
      bondMoney: "",
      sumPayable: "",
      orderNo: "",

      // 获取支付数据
      isStart: true,
      getTimeOutTimeOut: null,
    };
  },
  created() {
    this.getChannel();
    this.getRule();
    this.hotBooking();
    let dnList = this.$route.params.dnList;
    if (dnList != null && dnList.length > 0) {
      this.dnText = dnList.join("\n");
      this.dnNumber = dnList.length;
      this.dnSet = new Set(dnList);
    } else {
      let temp = this.$storage.getToLoginData();
      if (temp) {
        if (temp.dnList != null && temp.dnList.length > 0) {
          this.dnText = temp.dnList.join("\n");
          this.dnNumber = temp.dnList.length;
          this.dnSet = new Set(temp.dnList);
        }
        this.agree = temp.agree;
        this.channelSelect = temp.channelSelect;
        this.$storage.setToLoginData("");
      }
    }
  },
  methods: {
    // 获取协议
    getRule() {
      axios(`${bottomInfoUrl}/biddingBookingRules.json`).then((res) => {
        if (res != null && res.data != null) {
          this.ruleTitle = res.data.title;
          this.ruleContent = res.data.content;
        }
      });
      axios(`${bottomInfoUrl}/biddingBookingSeriveRules.json`).then((res) => {
        if (res != null && res.data != null) {
          this.seriveRuleTitle = res.data.title;
          this.seriveRuleContent = res.data.content;
        }
      });
    },
    // 获取通道
    async getChannel() {
      let res = await bookingChannel();
      this.channelList = res;
    },
    // 函数防抖获取输入框中的域名
    getDNNumber: debounce(function () {
      let temp = this.dnText.split("\n");
      this.dnNumber = temp.filter((item) => {
        return !item.match(/^[ ]*$/);
      }).length;
    }, 200),
    // 筛选出有用域名
    getAvailableDN() {
      let temp = this.dnText.split("\n").filter((item) => {
        return !item.match(/^[ ]*$/);
      });
      let dnList = temp.map((item) => trimStr(item));
      this.dnSet = new Set(dnList);
      this.dnText = [...this.dnSet].join("\n");
      this.dnNumber = this.dnSet.size;
    },
    // 校验域名
    async batchBookingfilter() {
      if (!this.$token.get()) {
        this.loginModelShow = true;
        return;
      }
      let list = [...this.dnSet];
      if (list.length <= 0) {
        this.$Message.warning("请至少输入一个域名");
        return;
      }
      if (this.channelSelect == null || this.channelSelect == "") {
        this.$Message.warning("请选择预订通道");
        return;
      }
      if (!this.agree) {
        this.$Message.warning(
          "请同意《抢注预订服务协议》并已阅读《抢注预订须知》"
        );
        return;
      }
      this.loading = true;
      let data = {
        domainNames: [...this.dnSet],
        channelId: this.channelSelect,
      };
      let res = await batchBookingfilter(data);
      if (res.code == 200) {
        this.sucList = res.data.sucList;
        this.failList = res.data.failList;
        this.checkResultModalShow = true;
      }
      this.loading = false;
    },
    // 获取推荐预订
    async hotBooking() {
      let res = await hotBooking();
      if (res.code == 200) {
        this.recommendList = res.data.bookingList;
      }
    },
    // 将推荐预订加入到列表中
    add(name) {
      if (this.dnSet.has(name)) {
        this.$Message.warning("列表中已经存在这个域名");
      } else {
        this.dnSet.add(name);
        this.dnText += `\n${name}`;
      }
    },
    // 删除元素
    deleteItem(index) {
      this.sucList.splice(index, 1);
    },
    // 检查元素后确认预订
    checkSubmit() {
      for (let i in this.channelList) {
        if (this.channelList[i].id == this.channelSelect) {
          this.selectChannelName = this.channelList[i].channelName;
          this.selectBookPrice = this.channelList[i].bookPrice;
          this.selectBookBond = this.channelList[i].bookBond;
          break;
        }
      }
      this.orderCheckModalShow = true;
    },
    // 订单确认提交
    async orderCheckSubmit() {
      this.orderCheckLoading = true;
      let data = {
        channelId: this.channelSelect,
        domainNames: this.sucList.map((item) => item.domainName),
      };
      let res = await createBatchOrder(data);
      if (res.code == 200) {
        this.orderCheckModalShow = false;
        this.checkResultModalShow = false;
        this.payModalShow = true;
        this.bondMoney = res.data.bond;
        this.sumPayable = res.data.amount;
        this.$store.commit("setBalance", res.data.balance);
        this.orderNo = res.data.orderNo;
      }
      this.orderCheckLoading = false;
    },
    // 开始付款
    startPay() {
      if (this.isStart) {
        this.isStart = false;
        this.startSocket();
      }
    },
    // 获取订单状态
    // async getOrderStatus() {
    //   let res = await getOrderStatus(this.orderNo);
    //   if(res.code == 200) {
    //     console.log(res.data);
    //     this.payModalShow = false
    //     this.orderSuccessModalShow = true
    //   } else {
    //     this.getTimeOutTimeOut = setTimeout(() => {
    //       this.getOrderStatus();
    //     }, 2000);
    //   }
    // },
    // webScoket发送消息
    sendMessage(txt) {
      this.webSocket.send(txt);
    },
    // webScoket异常重连
    resetConnect() {
      this.connectCount = this.connectCount || 0;
      if (!this.webSocketInterval) {
        // console.log("开始webSocket重连");
        this.webSocketResetInterval = setInterval(() => {
          this.connectCount += 1;
          if (this.connectCount <= 5) {
            this.startSocket();
            this.webSocketResetInterval &&
              clearInterval(this.webSocketResetInterval);
          }
        }, 1000);
      }
    },
    // 开启webScoket
    startSocket() {
      this.messageTotal = 0;
      this.webSocket = new WebSocket(
        `${webScoketUrl}/web/webSocket/pay/${this.orderNo}/${this.$token.get()}`
      );
      // 接收消息事件
      this.webSocket.onmessage = (e) => {
        // console.log(e);
        if (e.data === "open:suc") {
          this.sendMessage("start");
          this.heartInterval = setInterval(() => {
            if (this.messageTotal === 10) {
              this.sendMessage("heart");
              this.messageTotal = 0;
            }
            this.messageTotal += 1;
          }, 1000);
        }
        if (e.data.indexOf("msg:") != -1) {
          let message = e.data.split("msg:")[1];
          this.messageTotal = 0;
          let info = JSON.parse(message);
          if (info != null) {
            if (info.result == "true") {
              this.sendMessage("stop");
              this.payModalShow = false;
              this.orderSuccessModalShow = true;
              this.heartInterval && clearInterval(this.heartInterval);
            }
          }
        }
        if (e.data.indexOf("rec:stop") != -1) {
          this.webSocket.close();
        }
      };
      // 关闭事件
      // this.webSocket.onclose = () => {
      //   this.resetConnect();
      // };
      // 连接失败事件
      this.webSocket.onerror = () => {
        this.resetConnect();
      };
    },
    // 去登陆
    toLogin() {
      let dnList = [...this.dnSet];
      this.$storage.setToLoginData({
        dnList: dnList,
        channelSelect: this.channelSelect,
        agree: this.agree,
      });
      window.location.href = "/login";
    },
  },
  beforeDestroy() {
    // clearTimeout(this.getTimeOutTimeOut);
    if (!this.isStart) {
      if (this.webSocket) this.sendMessage("stop");
      this.heartInterval && clearInterval(this.heartInterval);
      this.webSocketResetInterval && clearInterval(this.webSocketResetInterval);
    }
  },
};
</script>

<style lang="scss" scoped>
.batch-booking-area {
  background-color: #f7f7f7;
  padding-bottom: 20px;

  .left-area {
    width: 750px;
    .box {
      background: #ffffff;
      border: 1px solid #eaeaea;

      .top-area {
        padding: 20px 30px 0;
      }

      .button {
        @include btn-s(0 13px, 25px, 4px);
        font-size: 14px;
        transition: border-color 0.3s, color 0.3s;
        border: 1px solid #898989;
        color: #3d3d3d;

        &:hover {
          color: #f9521f;
          border-color: #f9521f;
        }
      }

      .check-area {
        margin: 20px 0 0 30px;
        color: #3d3d3d;

        span {
          @include h-c(null, null, #1c9cdf, rgba(#1c9cdf, 0.7));
          cursor: pointer;
        }
      }

      .submit-button {
        @include size(140px, 40px);
        @include btn-s(null, 40px, 5px);
        @include h-c(#f9521f, rgba(249, 82, 31, 0.8), #fff);
        margin: 36px auto 30px;
      }

      .book-result-area {
        margin: 9px 0 15px;
        font-size: 14px;
        .icon {
          display: inline-block;
          @include size(24px);
          margin-right: 8px;
          @include bg-setting("true");
          font-size: 14px;
        }
      }
    }
  }
  .right-area {
    width: 435px;
    background: #ffffff;
    border: 1px solid #eaeaea;

    .button-size {
      @include size(80px, 26px);
      font-size: 12px;
      line-height: 26px;
    }
  }
  .bottom-area {
    margin-top: 15px;
    width: 100%;
    background: #ffffff;
    border: 1px solid #eaeaea;
    padding: 20px 30px;

    p {
      font-size: 14px;
      color: rgba($color: #3d3d3d, $alpha: 0.8);
      line-height: 1.5;
      word-break: break-all;
      margin-top: 18px;
      transition: color 0.3s;
      &:hover {
        color: #f9521f;
      }
    }
  }
}
.number-tips {
  position: absolute;
  bottom: 10px;
  right: 10px;
}
.b-b-order-check-modal-main {
  padding: 10px 30px;
}
</style>
